package com.cuz.for2024;

public class T29 {

    public int divide(int dividend, int divisor) {
        if (dividend == 0) {
            return 0;
        }
        if (divisor == 1) {
            return dividend;
        }
        if (divisor == -1) {
            if (dividend > Integer.MIN_VALUE) {
                return -dividend;
            }
            return Integer.MAX_VALUE;
        }

        boolean neg = true;
        if (dividend > 0 && divisor > 0) {
            neg = false;
        }
        if (dividend < 0 && divisor < 0) {
            neg = false;
        }
        long dividendL = dividend < 0 ? -(long)dividend : (long)dividend;

        long divisorL = divisor < 0 ? -(long)divisor : (long)divisor;
        long res = div(dividendL, divisorL);
        if (neg) {
            res = -res;
        }
        return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res;
    }

    private long div(long dividend, long divisor) {
        if (dividend < divisor) {
            return 0;
        }
        long count = 1;
        long temp = divisor;
        while (temp + temp <= dividend) {
            count = count + count;
            temp = temp + temp;
        }
        return count + div(dividend - temp, divisor);
    }

    public static void main(String[] args) {
        System.out.println(new T29().divide(-2147483648, 2));
    }
}
